package com.webserver.controller;

import com.webserver.core.ClientHandler;
import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;

public class UserController {
    private static File USer_DIR=new File("./users");
    private static File staticDir;

    static {
        if (!USer_DIR.exists()) {
            USer_DIR.mkdirs();
        }
        try {
            staticDir=new File(ClientHandler.class.getClassLoader().getResource("./static").toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }



    public void reg(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理用后注册");
        //1获取用户表单提交上来的数据
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        String nickname = request.getParameters("nickname");
        String ageStr = request.getParameters("age");
        System.out.println(username + "," + password + "," + nickname + "," + ageStr);
        if (username==null||password==null||nickname==null||ageStr==null||!ageStr.matches("[0-9]+")){
            File file=new File(staticDir,"/myweb/reg_fail.html");
            response.setContentFile(file);
            return;
        }

//2将用户信息以一个User实例形式表示，并序列化到文件中
        int age=Integer.parseInt(ageStr);
        User user=new User(username,password,nickname,age);

        File userFile=new File(USer_DIR,username+"obj");
         //判断是否重复用户
        if (userFile.exists()){
            File file=new File(staticDir,"/myweb/have_user.html");
            response.setContentFile(file);
            return;
        }
        try(
        FileOutputStream fos=new FileOutputStream(userFile);
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);
            File file=new File(staticDir,"/myweb/reg_success.html");
            response.setContentFile(file);
        }catch (IOException e){};
        System.out.println("处理用户注册完毕");
    }
}
